<template>
  <div class="list-pages white-bg">
    <div class="search-form-box">
      <a-form
        :model="formState"
        name="horizontal_login"
        :label-col="labelCol"
        autocomplete="off"
        @finish="onFinish"
      >
        <a-row :gutter="[16, 16]">
          <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" v-show="expand">
            <a-form-item label="名称" name="name">
              <a-input v-model:value="formState.name" placeholder="请输入器材名称"> </a-input>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="6" v-show="expand">
            <a-form-item label="分类" name="class">
               <a-select v-model:value="formState.class" placeholder="请选择分类">
                <a-select-option v-for="option in equipmentOptions" :key="option.value" :value="option.value">
                  {{ option.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="6">
            <a-form-item>
              <div class="search-btn-box" :class="{ pt: expand }">
                <a-button
                  :icon="h(SearchOutlined)"
                  type="primary"
                  html-type="submit"
                  class="search-btn"
                  >查询</a-button
                >
                <a-button
                  :icon="h(ReloadOutlined)"
                  class="reset-btn"
                  @click="resetForm"
                  >清空</a-button
                >
                <a
                  class="expand-btn"
                  style="font-size: 12px; margin-left: 12px"
                  @click="expand = !expand"
                >
                  <template v-if="expand">
                    <UpOutlined />
                  </template>
                  <template v-else>
                    <DownOutlined />
                  </template>
                  {{ expand ? "收起查询" : "展开查询" }}
                </a>
              </div>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="opt-button-box">
      <a-button type="primary" class="btn" @click="handleAdd">
        <img src="/icons/common/icon-add.png" class="icon" />新增设备</a-button
      >
      <a-button class="btn" @click="handleExport" :loading="exportLoading">
        <img src="/icons/common/icon-export.png" class="icon" />导出设备</a-button
      >
    </div>
    <div class="table-wrapper" ref="tableRef">
      <a-table
        class="table-box"
        row-key="id"
        :columns="columns"
        :dataSource="tableData"
        :loading="loading"
        :row-class-name="
          (_record, index) => (index % 2 === 1 ? 'table-striped' : null)
        "
        sticky
        :scroll="{ y: true, x: 1100 }"
        :pagination="pagination"
        @change="onChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex == 'equipment_category_name'">
            
          </template>

          <template v-if="column.dataIndex == 'enabled'">
             {{ record.enabled ? '启用' : '禁用' }}
          </template>

          <template v-if="column.dataIndex == 'operation'">
            <a-button type="link" class="link" @click="handleDetail(record)">
              查看
            </a-button>
            <a-button type="link" class="link" @click="handleEdit(record)">
              编辑
            </a-button>
            
            <a-popconfirm v-if="!record.enabled" title="确认上架?" @confirm="handleToggleStatus(record, true)">
              <a-button type="link" class="link"> 上架 </a-button>
            </a-popconfirm>
             <a-popconfirm v-if="record.enabled" title="确认下架?" @confirm="handleToggleStatus(record, false)">
              <a-button type="link" class="link"> 下架 </a-button>
            </a-popconfirm>
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>
<script setup>
import { ref, computed, h, onMounted, onUnmounted } from "vue";
import {
  SearchOutlined,
  ReloadOutlined,
  DownOutlined,
  UpOutlined,
} from "@ant-design/icons-vue";
import { useRouter } from "vue-router";
import { useGlobalStore } from "@/store/modules/global";
import { message } from "ant-design-vue";
import administratorApi from "@/api/administrator";
const store = useGlobalStore();
const router = useRouter();
const labelCol = { style: { width: "80px" } };

const formState = ref({
  name: "",
  status: [],
});

const loading = ref(false);
const exportLoading = ref(false);

// 设备选项相关变量
const equipmentOptions = ref([]);
const equipmentOptionsLoading = ref(false);

const resetForm = () => {
  formState.value = {
   name: "",
  status: [],
  };
  getEquipmentList();
};
const windowWidth = ref(window.innerWidth);
const expand = ref(true);
onMounted(() => {
  windowWidth.value = window.innerWidth;
  if (windowWidth.value > 768) {
    expand.value = true;
  } else {
    expand.value = false;
  }
  window.addEventListener("resize", () => {
    windowWidth.value = window.innerWidth;
    if (windowWidth.value > 768) {
      expand.value = true;
    } else {
      expand.value = false;
    }
  });
  
  // 初始化加载数据
  getEquipmentList();
  // 初始化加载设备选项
  getEquipmentOptions();
});
onUnmounted(() => {
  window.removeEventListener("resize", () => {});
});

function onFinish(values) {
  console.log("Success:", values);
  current.value = 1; // 重置到第一页
  getEquipmentList();
}
const tableData = ref([]);

// 获取设备列表数据
const getEquipmentList = async () => {
  try {
    loading.value = true;
    const params = {
      args: {
        current: current.value,
        pageSize: pageSize.value,
        keyword: formState.value.name || undefined,
        categoryId: formState.value.status?.length ? formState.value.status : undefined,
        enabled: undefined,
        dateRange: undefined,
        sort: undefined,
        filter: undefined,
        idArray: undefined,
      }
    };
    
    const response = await administratorApi.ExperimentEquipmentPagedList(params);
    console.log('API响应:', response);
    
    if (response && response.data) {
      // 根据实际API返回结构处理数据
      const rawData = response.data.data || response.data || [];
      
      // 重构数据，将嵌套的equipment信息提取到顶层
      tableData.value = rawData.map(item => ({
        // 保留原有的实验设备关联信息
        experiment_id: item.experiment_id,
        equipment_id: item.equipment_id || item.id,
        amount: item.amount,
        sort: item.sort,
        remark: item.remark,
        
        // 将equipment对象的属性提取到顶层，方便表格显示
        name: item.equipment?.name || item.name || '',
        model: item.equipment?.model || item.model || '',
        code: item.equipment?.code || item.code || '',
        brand: item.equipment?.brand || item.brand || '',
        introduce: item.equipment?.introduce || item.introduce || '',
        enabled: item.equipment?.enabled !== undefined ? item.equipment.enabled : (item.enabled !== undefined ? item.enabled : false),
        equipment_category_id: item.equipment?.equipment_category_id || item.equipment_category_id || 0,
        equipment_category_name: item.equipment?.equipment_category_name || item.equipment_category_name || '',
        image: item.equipment?.image || item.image || '',
        
        // 保留完整的equipment对象，以备需要
        equipment: item.equipment || item
      }));
      
      total.value = response.data?.total || response.total || rawData.length;
      console.log('重构后的设备列表数据:', tableData.value);
    } else {
      console.error('获取设备列表失败:', response?.errors || '未知错误');
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取设备列表出错:', error);
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};


const columns = ref([
  
  {
    dataIndex: "name",
    title: "名称",
    ellipsis: true,
    width: 180
  },
  {
    dataIndex: "equipment_category_name",
    title: "分类",
    width: 110,
  },
  {
    dataIndex: "created",
    title: "入库时间",
    width: 200,
  },
  // {
  //   dataIndex: "code",
  //   title: "设备编码",
  //   width: 120,
  // },
  // {
  //   dataIndex: "amount",
  //   title: "数量",
  //   width: 80,
  // },
  {
    dataIndex: "enabled",
    title: "状态",
    width: 100,
  },
  // {
  //   dataIndex: "introduce",
  //   title: "介绍",
  //   ellipsis: true,
  //   width: 150,
  // },
  {
    dataIndex: "operation",
    title: "操作",
    width: 240,
    align: "center",
    fixed: "right",
  },
]);

const onChange = (page) => {
  console.log(page);
  current.value = page.current;
  pageSize.value = page.pageSize;
  getEquipmentList();
};
const current = ref(1);
const pageSize = ref(10);
const total = ref(0);
const pagination = computed(() => ({
  position: ["bottomCenter"],
  total: total.value,
  current: current.value,
  pageSize: pageSize.value,
  showSizeChanger: true,
  size: "large",
  showTotal: (total) => `共 ${total} 条`,
}));

const handleAdd = () => {
  store.setSubTitle("新增设备");
  router.push({
    path: "equipment-management-option"
  });
};

const handleDetail = (data) => {
  store.setSubTitle("查看设备信息");
  router.push({
    path: "equipment-management-detail",
    query: {
      experiment_id: data.experiment_id,
      equipment_id: data.equipment_id || data.id
    }
  });
}
const handleEdit = (data) => {
  console.log("编辑设备", data);
  store.setSubTitle("编辑设备");
  router.push({
    path: "equipment-management-option",
    query: {
      experiment_id: data.experiment_id,
      equipment_id: data.equipment_id || data.id
    }
  });
};

const handleToggleStatus = async (data, enabled) => {
  try {
    console.log(enabled ? "上架设备" : "下架设备", data);
    
    // 先获取设备详情，获取完整的数据
    const detailParams = {
      equipment_id: data.equipment_id || data.id
    };
    
    console.log("获取设备详情参数:", detailParams);
    
    const detailResponse = await administratorApi.ExperimentEquipmentFetchModel(detailParams);
    
    if (detailResponse) {
      // 使用详情返回的数据，原模原样，只修改enabled字段
      const updateData = {
        ...detailResponse,
        enabled: enabled
      };
      
      console.log("更新设备参数:", updateData);
      
      // 调用更新API
      const updateResponse = await administratorApi.ExperimentEquipmentUpdate(updateData);
      
      if (updateResponse) {
        message.success(enabled ? "设备上架成功" : "设备下架成功");
        // 重新加载列表数据
        getEquipmentList();
      } else {
        message.error(updateResponse?.errors?.[0] || (enabled ? "上架失败" : "下架失败"));
      }
    } else {
      message.error("获取设备详情失败");
    }
  } catch (error) {
    console.error(enabled ? "上架设备失败:" : "下架设备失败:", error);
    message.error(enabled ? "上架失败，请稍后重试" : "下架失败，请稍后重试");
  }
};

// 图片加载错误处理
const handleImageError = (event) => {
  event.target.style.display = 'none';
  event.target.parentNode.innerHTML = '<div style="width: 60px; height: 40px; background: #f5f5f5; border-radius: 4px; display: flex; align-items: center; justify-content: center; color: #999; font-size: 12px;">加载失败</div>';
};

// 导出设备列表
const handleExport = async () => {
  try {
    exportLoading.value = true;
    
    // 构建导出参数，使用当前搜索条件
    const exportParams = {
      args: {
        current: current.value,
        pageSize: pageSize.value,
        keyword: formState.value.name || undefined,
        categoryId: formState.value.status?.length ? formState.value.status : undefined,
        enabled: undefined,
        dateRange: undefined,
        sort: undefined,
        filter: undefined,
        idArray: undefined,
      }
    };
    
    console.log("导出参数:", exportParams);
    
    // 调用导出API
    const response = await administratorApi.ExperimentEquipmentExport(exportParams);
    
    console.log("导出响应:", response);
    
    if (response && response.file) {
      const fileData = response.file;
      
      // 处理Base64编码的文件内容
      const base64Content = fileData.fileContents;
      const contentType = fileData.contentType || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
      const fileName = fileData.fileDownloadName || '虚拟实验关联实验器材_导出.xlsx';
      
      try {
        // 将Base64字符串转换为二进制数据
        const binaryString = atob(base64Content);
        const bytes = new Uint8Array(binaryString.length);
        for (let i = 0; i < binaryString.length; i++) {
          bytes[i] = binaryString.charCodeAt(i);
        }
        
        // 创建Blob对象
        const blob = new Blob([bytes], { type: contentType });
        
        // 创建下载链接
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = fileName;
        
        // 触发下载
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        // 清理URL对象
        window.URL.revokeObjectURL(url);
        
        message.success("导出成功");
      } catch (decodeError) {
        console.error("文件解码失败:", decodeError);
        message.error("文件解码失败，请稍后重试");
      }
    } else {
      const errorMessage = response?.errors?.[0] || "导出失败";
      console.error("导出失败:", response);
      message.error(errorMessage);
    }
  } catch (error) {
    console.error("导出设备列表失败:", error);
    message.error("导出失败，请稍后重试");
  } finally {
    exportLoading.value = false;
  }
};

// 获取设备分类选项
const getEquipmentOptions = async (keyWords = "") => {
  try {
    equipmentOptionsLoading.value = true;
    const response = await administratorApi.EquipmentCategoryOptions({});
    
    if (response) {
      equipmentOptions.value = response;
      console.log('设备分类选项数据:', response);
    } else {
      console.error('获取设备分类选项失败');
      equipmentOptions.value = [];
    }
  } catch (error) {
    console.error('获取设备分类选项出错:', error);
    equipmentOptions.value = [];
  } finally {
    equipmentOptionsLoading.value = false;
  }
};

// 处理设备搜索
const handleEquipmentSearch = (value) => {
  console.log('搜索设备:', value);
  getEquipmentOptions(value);
};

// 处理设备选择变化
const handleEquipmentChange = (value) => {
  console.log('选择设备:', value);
  // 可以在这里添加额外的逻辑，比如自动触发搜索
};
</script>
<style lang="less" scoped>
.list-pages {
  height: 100%;
  padding: 0 16px;
  display: flex;
  flex-direction: column;
  .search-box {
    display: flex;
    align-items: center;
    padding: 18px 0;
    flex-wrap: wrap;
    border-bottom: 1px solid #e5e7eb;
    .search-select {
      width: 120px;
    }
    .line {
      width: 1px;
      height: 16px;
      margin: 0 12px;
      background: #bec4ca;
      @media screen and (max-width: 768px) {
        display: none;
      }
    }
    .search-input-box {
      flex: 1;
      display: flex;
      align-items: center;
      @media screen and (max-width: 768px) {
        width: 100%;
        margin-top: 16px;
        justify-content: space-between;
      }
    }
    .search-input {
      flex: 1;
    }
    .search-btn {
      width: 60px;
      height: 32px;
      background: #2776ff;
      border-radius: 4px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      font-size: 14px;
      color: #ffffff;
      text-align: center;
      line-height: 32px;
    }
  }
  .table-wrapper {
    width: 100%;
    flex: 1;
    overflow: hidden;
    .table-box {
      height: 100%;
    }
  }
  .list-box {
    width: 100%;
    box-sizing: border-box;
    padding-top: 16px;
    overflow: auto;
    display: grid;
    gap: 16px;
    margin: 0 auto;
    grid-template-columns: repeat(auto-fill, minmax(261px, 1fr));
    justify-content: space-between;
    .list-item {
      width: 261px;
      background: #ffffff;
      border: 1px solid #e6ebf1;
      border-radius: 8px;
      box-sizing: border-box;
      padding: 8px;
      margin: auto;
      position: relative;
      cursor: pointer;
      &:hover {
        border: 1px solid #2776ff;
        box-shadow: 12px 12px 12px 0px rgba(39, 118, 255, 0.1);
      }
      .item-collect {
        position: absolute;
        top: 0;
        right: 0;
        cursor: pointer;
        width: 32px;
        height: 32px;
        background: rgba(0, 0, 0, 0.4) url(@/assets/icon-collet.png) no-repeat
          center center;
        border-radius: 0 8px 0 12px;
        &.cur {
          background: #ffffff url(@/assets/icon-collet-cur.png) no-repeat center
            center;
          border-radius: 0 8px 0 12px;
        }
      }

      .list-img {
        width: 245px;
        height: 249px;
        background: #f3f3f3;
        border: 1px solid #e6ebf1;
        border-radius: 8px;
        box-sizing: border-box;
        img {
          width: 100%;
          height: 100%;
          border-radius: 8px;
        }
      }
      .list-content {
        padding: 14px 0 6px;
        display: flex;
        flex-direction: column;
        .content-title {
          font-family: PingFangSC-Medium;
          font-weight: 500;
          font-size: 16px;
          color: #31323a;
          margin-bottom: 10px;
          line-height: 24px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .content-col {
          display: flex;
          align-items: center;
          justify-content: space-between;
          .col-user {
            display: flex;
            align-items: center;
            .user-img {
              width: 26px;
              height: 26px;
              border-radius: 50%;
            }
            .user-name {
              font-family: PingFangSC, PingFang SC;
              font-weight: 400;
              font-size: 12px;
              color: #262626;
              line-height: 16px;
              text-align: left;
              font-style: normal;
            }
          }
          .col-date {
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 12px;
            color: #8c8c8c;
            line-height: 16px;
            text-align: center;
            font-style: normal;
          }
        }
      }
    }
  }

  .pagination-box {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
